using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using ebookreader.Resources;

namespace ebookreader
{
    public class BookmarkList : Menu
    {
        #region Fields

        public List<BoxedLabelScrollableButton> buttons = new List<BoxedLabelScrollableButton>();
        RenderableObject backgrounds, pop_up_box;
        //BoxedLabelButton back, go_to_page;
        VirtualKeyboard keyboard;
        TextureButton backspace;
        Reader reader;


        //SpriteFont font;
        #endregion
        State currentState;
        public BookmarkList(Game game, Reader reader, IInputManager input_manager)
            : base(game, new Rectangle(390, 163, 226, 195), input_manager)            
        {
            this.reader = reader;
            sprite_batch = Game.Services.GetService(typeof(SpriteBatch)) as SpriteBatch;
            input_manager.OnTap += new InputManager.Tap(OnTap);
            input_manager.OnDoubleTap += new InputManager.Tap(OnDoubleTap);
            currentState = Game.Services.GetService(typeof(State)) as State;
        }

        public override void Initialize()
        {
            base.Initialize();
        }



        Vector2 dest = new Vector2(107, 431);
        Vector2 now = new Vector2(225, 351);
        public override void Draw(GameTime gameTime)
        {
            sprite_batch.Begin();
            
            //sprite_batch.DrawString(font, Lang.Go_to_page, new Vector2(400 - font.MeasureString(Lang.Go_to_page).X, 131), Color.Black);

            //sprite_batch.DrawString(Game.Content.Load<SpriteFont>("Fonts/Arial"), "PROVA POPUP", new Vector2(300,200), Color.Green);
            DrawOrder = 6;
            sprite_batch.End();
            base.Draw(gameTime);
            sprite_batch.Begin();
            sprite_batch.Draw(list_mask, new Vector2(378, 116), Color.White);
            scrollbar.Draw(sprite_batch, (float)gameTime.ElapsedGameTime.TotalSeconds);
            sprite_batch.End();
        }

        Texture2D popup_read_body, popup_back, button_ring, back, key, bookmark_el, long_button_ring, list_mask;
        SpriteFont font;
        ScrollBar scrollbar;
        protected override void LoadContent()
        {
            bookmark_el = Game.Content.Load<Texture2D>("Definitivo/bookmark_list_element");

            list_mask = Game.Content.Load<Texture2D>("Definitivo/bookmark_list_mask");

            font = Game.Content.Load<SpriteFont>("Fonts/menu_piccolo");


            scrollbar = new ScrollBar(6, new Rectangle(634, 164, 12, 190), Game.Content.Load<Texture2D>("todo/white"), Color.Black*0.2f, Color.Black*0.6f);

            int j = 0;
            foreach (var book in reader.currentState.currentBook.bookmarksList)
            {
                addBookmarkButtonList(book, j++);
            }

            base.LoadContent();
        }



        public override void Update(GameTime gameTime)
        {

            if (!dragging && buttons.Count>0)
            {
                offsetPosition.Y += forceY;
                if (Math.Abs(forceY) >= 1f)
                    forceY = MathHelper.Lerp(forceY, 0.0f,
                        (float)gameTime.ElapsedGameTime.TotalSeconds * (float)Math.Max(60 / Math.Abs(forceY), 4f));
                else
                    forceY = 0.0f;


                var fixPosition = 10000.0f;
                var firstIndex = 0;
                int i = 0;
                for (; i<buttons.Count;i++)                
                {
                    var m = buttons[i];
                    //if (bookOrder[i] > 0 && bookOrder[i] > books_buttons.Count)
                    //    continue;
                    if (i == selectedBookmar)
                        m.box_color = new Color(255, 146, 18);
                    else
                        m.box_color = new Color(226, 226, 226);

                    m.splitLabel();
                    if (Math.Abs(fixPosition) > Math.Abs((m.box_position.Y + offsetPosition.Y) - (area.Top)))
                    {
                        fixPosition = m.box_position.Y + offsetPosition.Y - (area.Top);
                        firstIndex = i;
                    }
                    m.active = true;
                    //if (m.box_position.Y + offsetPosition.Y < LIST_MARGIN - 10 ||
                    //    m.box_position.Y + offsetPosition.Y > GraphicsDevice.Viewport.Height - title_box_heigth)
                    //    m.active = false;
                   
                }
                scrollbar.firstelement=firstIndex;
                scrollbar.total_elements = buttons.Count;
                if (fixPosition != 0.0f)
                    offsetPosition.Y =
                        MathHelper.Lerp(offsetPosition.Y, offsetPosition.Y - fixPosition,
                        (float)gameTime.ElapsedGameTime.TotalSeconds * 5);

            }

            base.Update(gameTime);
        }


        int LEFT_MARGIN = 80, TOP_MARGIN = 100, SPACING = 20;
        Texture2D ui_bookmark_box;
        public int selectedBookmar = 0;
        
        public void addBookmarkButtonList(BookMark book)
        {
            addBookmarkButtonList(book, buttons.Count);
        }
        
        private void addBookmarkButtonList(BookMark book, int index)
        {
            var nb = new BoxedLabelScrollableButton(sprite_batch, bookmark_el,
                new Vector2(area.Left, area.Top + index * (bookmark_el.Height)),
                   font, new Vector2(0, 0), book.name, Color.Black, Color.White, currentState.options);
            nb.OnPress += new Press((MenuEntry m) =>
            {
                var selected = (BoxedLabelScrollableButton)m;
                selectedBookmar = buttons.IndexOf(selected);
                
                //reader.current_page = reader.findPage(book.word);
                ////SaveBookList(books);
                //Game.Components.Remove(this);
                //this.Dispose();
            });
            nb.OnDoubleTapped += new Press((me) =>
                {
                    var selected = buttons.IndexOf((BoxedLabelScrollableButton)me);
                    if (selected < reader.currentState.currentBook.bookmarksList.Count)
                        reader.current_page = reader.findPage(reader.currentState.currentBook.bookmarksList[selected].word);
                });
            buttons.Add(nb);
            entries.Add(nb);
            selectedBookmar = buttons.Count - 1;
        }

        public void removeBookmark(int i)
        {
            try
            {
                if (buttons.Count <= 0 && i < buttons.Count)
                    return;
                reader.currentState.currentBook.bookmarksList.RemoveAt(i);
                entries.Remove(buttons[i]);
                buttons.RemoveAt(i);

                for (; i < buttons.Count; i++)
                {
                    buttons[i].box_position = new Vector2(area.Left, area.Top + 5 + i * (bookmark_el.Height));
                }
                selectedBookmar = Math.Min(selectedBookmar, buttons.Count);
            }
            catch (Exception) { }
        }
    }
}
